using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace UDPActiveMonitor
{
    class ReadMessagesWorker : BackgroundWorker
    {
        
        IPEndPoint ep;
        private UdpClient udpc,udpcSync;
       Msg eMess;
        byte[] bite; 
        string tmpMessage, tmpLabel;
        Msg oMess;
        
        protected override void OnDoWork(DoWorkEventArgs eThread)
        {

            int iiii = 1;
            string[] mydata;
            oMess = (Msg)eThread.Argument;
            if (oMess.mtype == Msg.MessageType.service)
                udpc = new UdpClient(7790);
            if (oMess.mtype == Msg.MessageType.sync)
                udpc = new UdpClient(7791);
            if (oMess.mtype == Msg.MessageType.vin)
                udpc = new UdpClient(7792);

            ep = null;
            int iei = 0;
            while (iiii == 1)
            {
                eMess = new Msg();
                if (eThread.Cancel == true)
                    return;
                eMess.mtype = oMess.mtype;
                byte[] rdata = udpc.Receive(ref ep);
                string sdata = Encoding.ASCII.GetString(rdata);
                if (sdata == "End Process")
                    return;
                eMess.msgDT = DateTime.Now;
                eMess.message = sdata;


                int idx;
                byte[] bte;
                bte = new byte[1];
                bte[0] = 249;
                idx = sdata.LastIndexOf(Encoding.ASCII.GetString(bte));
                if (idx > 0)
                    tmpMessage = sdata.Substring(0, idx);
                else
                    tmpMessage = "NN";
                tmpLabel = sdata.Substring(idx + 1);
                if (tmpLabel.Length > 50)
                    tmpLabel = tmpLabel.Substring(tmpLabel.Length - 50);
                eMess.address = ep.Address;

                this.ReportProgress(iei,eMess);
                Thread.Sleep(3);
                iei++;
                
            }

        }
        private void InitializeComponent()
        {
            // 
            // ReadMessagesWorker
            // 
            this.WorkerSupportsCancellation = true;

        }

   

    }
}
